package world.snowcrystal.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import world.snowcrystal.common.ErrorCode;
import world.snowcrystal.exception.BusinessException;
import world.snowcrystal.model.entity.Picture;
import world.snowcrystal.service.PictureService;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 图片服务实现类，用于抓取来自 <a href="www.bing.cn">bing</a> 的图片
 * @author tianqing
 */
@Service
public class PictureServiceImpl implements PictureService {

    public static String URL = "https://cn.bing.com/images/search?q=%s&first=%s";

    @Override
    public Page<Picture> searchPicture(String searchText, long pageNum, long pageSize) {
        long current = (pageNum - 1) * pageSize;
        String url = String.format(URL, searchText, current);
        Document doc;
        try {
            doc = Jsoup.connect(url).get();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据获取异常");
        }
        Elements elements = doc.select(".iuscp.isv");
        List<Picture> pictures = elements.stream()
                .parallel()
                .limit(pageSize)
                .map((element -> {
                    String m = element.select(".iusc").get(0).attr("m");
                    Map<String, Object> map = JSONUtil.toBean(m, Map.class);
                    String murl = (String) map.get("murl");
                    String title = element.select(".inflnk").get(0).attr("aria-label");
                    Picture picture = new Picture();
                    picture.setTitle(title);
                    picture.setUrl(murl);
                    return picture;
                }))
                .toList();
        Page<Picture> picturePage = new Page<>(pageNum, pageSize);
        picturePage.setRecords(pictures);
        return picturePage;
    }
}
